package com.example.producer.listener;

import java.time.LocalDateTime;

import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import com.example.common.model.Dog;

@Component
//@RocketMQTransactionListener(txProducerGroup = CommonConstant.MQ_TX_GROUP)
public class TradeOrderListener implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {

        try {

            String id3 = (String) message.getHeaders().get("id3");
            System.out.println("executeLocalTransaction, id3: " + id3);

            //            tradeOrderService.save1(tradeOrder);
            //            System.out.println(1 / 0);

            System.out.println("事务执行待确认. time: " + LocalDateTime.now());
            return RocketMQLocalTransactionState.UNKNOWN;

        } catch (Exception e) {
            System.out.println("发生异常, 回滚");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {

        //
        Long id = (Long) message.getHeaders().get("id3");
        System.out.println("checkLocalTransaction, id: " + id);

        Dog dog = (Dog) message.getPayload();
        System.out.println("事务执行接收消息: " + dog);

        // 查询
        System.out.println("事务执行已确认：成功. time: " + LocalDateTime.now());

        // 根据情况确认或回滚
        return RocketMQLocalTransactionState.COMMIT;
    }

}
